// 扩展2. 链表
/**
 * 
*/
#include <iostream>
#define __mark 2

#if __mark == 1
int main(void)
{
  struct node
  {
    int data;   // 存放的数据
    int id;     // 序号
    node *next; // 下一个节点指针
  };

  struct node *head, *p, *q;
  head = NULL;
  p = NULL;
  q = new node;
  q->id = 0;
  q->data = 0;
  q->next = NULL;
  std::cout << "请你输入第1个数据:";
  std::cin >> q->data;

  if (0 == q->data)
  {
    delete[] q;
    q = NULL;
  }
  else
  {
    head = q;

    while (q->data != 0)
    {
      if (p)
      {
        // 从第二个开始 有效数据计入节点
        p->next = q;
      }
      p = q;
      q = new node; // 重新分配内存
      q->next = NULL;
      q->id = p->id + 1;
      q->data = 0;
      std::cout << "请你输入第" << q->id + 1 << "个数据:";
      std::cin >> q->data;
    }

    delete[] q;
    q = NULL;
  }

  p = head;
  while (p)
  {
    std::cout << "id : " << p->id << " data : " << p->data << std::endl;
    p = p->next;
  }

  std::cout << "--------------delete----------------" << std::endl;

  p = head;
  q = head;
  while (p)
  {
    q = p->next;
    delete[] p;
    p = q;
  }
  q = NULL;
  p = NULL;
  head = NULL;

  // p = head;
  // while (p)
  // {
  //   std::cout << "id : " << p->id << " data : " << p->data << std::endl;
  //   p = p->next;
  // }

  printf("----------end---------------\n");
  return 0;
}

// #2 优化 #1
#elif __mark == 2
int main(void)
{
  struct node
  {
    int data;   // 存放的数据
    int id;     // 序号
    node *next; // 下一个节点指针
  };

  struct node *head, *p, *q;
  head = NULL;
  p = NULL;
  q = NULL;
  int a = 0;
  std::cout << "请输入第1个数据:";
  std::cin >> a;

  while (a != 0)
  {
    if (q)
    {
      p = q; // 保存上一个
      q = new node;
      p->next = q;
      q->id = p->id + 1;
    }
    else
    {
      q = new node;
      head = q;
      q->id = 0;
    }

    q->next = NULL;
    q->data = a;

    std::cout << "请输入第" << q->id + 2 << "个数据:";
    std::cin >> a;
  }

  std::cout << "\n--------------print----------------" << std::endl;
  p = head;
  while (p)
  {
    std::cout << "id : " << p->id << " data : " << p->data << std::endl;
    p = p->next;
  }

  std::cout << "\n--------------delete----------------" << std::endl;

  p = head;
  q = head;
  while (p)
  {
    q = p->next;
    delete[] p;
    p = q;
  }
  q = NULL;
  p = NULL;
  head = NULL;

  // p = head;
  // while (p)
  // {
  //   std::cout << "id : " << p->id << " data : " << p->data << std::endl;
  //   p = p->next;
  // }

  printf("----------end---------------\n");
  return 0;
}
#endif